package com.xiayuxuanmin.weixinpay.servlet;

import com.xiayuxuanmin.weixinpay.utils.PayCommonUtil;
import com.xiayuxuanmin.weixinpay.utils.QRUtil;
import com.xiayuxuanmin.weixinpay.utils.ZxingUtil;
import org.apache.log4j.Logger;
import org.jdom.JDOMException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 微信购买servlet
 * @Author xiayuxuanmin
 * @Date 2019/8/1
 * @Description
 */
public class BuyServlet extends HttpServlet {
    private Random random = new Random();

    private static Logger log = Logger.getLogger("wapshop_log");

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户要购买的商品
        req.setCharacterEncoding("UTF-8");
        String body = req.getParameter("body");//获取用户要购买的商品
        String price = "1";//微信的价格为分,这里测试直接指定为1分
        String order_id = random.nextInt(10000000)+"";//商品的订单号,实际开发中参考公司的产品要求生成实际订单号
        //生成二维码
        //二维码到底是什么,它其实是一个字符串的二进制数据,生成的一个图片
        //1 先得到二维码的原始字符串
            //按照微信的规则,生成字符串
        //2 将字符串转为二维码
        try {
            String result = PayCommonUtil.weixin_pay(order_id, order_id, body, price);//获取到二维码对应的字符串
            //获取二维码图片
            BufferedImage image = ZxingUtil.createImage(result, 300, 300);
            //跳转到页面,显示二维码,这里放入到session,在页面直接从session中取即可
            req.getSession().setAttribute("image",image);
            req.getSession().setAttribute("order_id",order_id);
            resp.sendRedirect(req.getContextPath()+"/payment.jsp");
        } catch (JDOMException e) {
            e.printStackTrace();
        }
    }
}
